<template>
  <TitleBar :value="buttons"
            :tip="debugTip"
            @click="handleClick"
            :closable="!isBack"
            :back="isBack"
            v-bind="$attrs" />
</template>

<script>
import WaybillMixin, { STATUS_CODES } from "./waybill.mixin";
import TitleBar from "@/components/basic/TitleBar.vue";
import { mapState } from "vuex";
export default {
  name: "WaybillTitleBar",
  components: { TitleBar },
  mixins: [WaybillMixin],
  inheritAttrs: true,
  props: {
    value: Object,
    isAll: [Boolean, Number],
    isBack: Boolean,
    oneBillFlag: [Boolean, String],
    closeFlag: Boolean,
    showCarrier: Boolean,
    isClose: [Boolean, String]
  },
  data () {
    return {
      // fromPath: null,
    };
  },
  computed: {
    ...mapState({
      tenantInfo: (state) => state.tenant.tenantInfo
    }),
    waybillId () {
      return this.waybill?.id || this.waybill?.waybillId;
    },
    status () {
      return Number(this.waybill?.status);
    },
    printTemplate () {
      return this.tenantInfo?.config?.printTemplate || [];
    },
    echo () {
      return this.waybill?.echo;
    },
    // 租户配置打印路由
    printPath () {
      const cstStatusPrint = {
        30: 'customerWaybillSignTemplate',
        40: 'customerWaybillReceiptTemplate',
        50: 'customerWaybillReceiptedTemplate'
      }
      const carrStatusPrint = {
        10: 'carrierWaybillWaitDispatchTemplate',
        20: 'carrierWaybillEntrustedTemplate',
        30: 'carrierWaybillSignTemplate',
        40: 'carrierWaybillReceiptTemplate',
        50: 'carrierWaybillReceiptedTemplate'
      }
      let path = null;
      let printName = this.showCarrier ? carrStatusPrint[this.status] : cstStatusPrint[this.status];
      this.printTemplate?.length && this.printTemplate.some((o) =>
        (path = printName === o.name ? o.value.split(";") : null)
      );
      console.log("=======path", path)
      if (this.echo && this.echo?.orderTypeName) {
        const echoPath = {
          "OEM直发": "TopOEMPrint",
          "干线直发": "TopUnOEMPrint",
          "经销商直发": "TopUnOEMPrint",
        }
        if (path.length && path.includes(echoPath[this.echo?.orderTypeName])) {
          return echoPath[this.echo?.orderTypeName]
        }
        return 'TransportPrint';
      } else {
        // 加加打印 配置模板且运单待签收且提货预约已确认
        if (path.includes('JiajiaPrint') && this.status === 30 && this.waybill?.pickCovenant?.pickCovenantStatus) {
          return 'JiajiaPrint';
        } else {
          return path && path.length ? path[0] : null;
        }
      }
    },
    // 有效打印路由
    effectivePaths () {
      return ['TransportPrint', 'TopOEMPrint', 'TopUnOEMPrint', 'JiajiaPrint'];
    },
    hasCloseBacklog () {
      // 有关单待办才显示关单审核按钮
      return this.waybill.close?.status === 20;
    },
    showPrintButton () {
      return (
        this.waybill.status === STATUS_CODES.WAIT_SIGN ||
        this.waybill.status === STATUS_CODES.WAIT_RECEIPT ||
        this.waybill.status === STATUS_CODES.RECEIPTED
      );
    },
    debugTip () {
      if (process.env.NODE_ENV === "development") {
        return this.waybill.status + " " + this.waybill.combineId;
      }
    },
    buttons () {
      return [
        {
          title: "同意",
          fulfill: this.handleAgree,
          type: "primary",
          hidden: this.oneBillFlag || !this.hasCloseBacklog || !this.isClose || this.isAll
        },
        // 拒绝关单
        {
          title: "拒绝",
          fulfill: this.handleRejectClose,
          type: "primary",
          hidden: this.oneBillFlag || !this.hasCloseBacklog || !this.isClose || this.isAll || this.waybill.isRootWaybill === 1
        },
        {
          title: "接收",
          fulfill: this.handleAccept,
          type: "primary",
          hidden: this.oneBillFlag || this.status !== 21 || this.isClose || this.isAll
        },
        // 拒绝接收
        {
          title: "拒绝",
          fulfill: this.handleReject,
          type: "primary",
          hidden: this.oneBillFlag || this.status !== 21 || this.isClose || this.isAll
        },
        {
          title: "回单",
          fulfill: this.handleReceipt,
          type: "primary",
          hidden: this.oneBillFlag || this.status !== 40 || this.isClose || this.isAll
        },
        {
          title: "签收",
          fulfill: this.handleSign,
          type: "primary",
          hidden: this.oneBillFlag || this.status !== 30 || this.isClose || this.isAll
        },
        {
          title: "撤销拆单",
          fulfill: this.handleCancelSplit,
          type: "primary",
          hidden: this.oneBillFlag || this.status !== -1 || this.isAll
        },
        {
          title: "撤销调度",
          fulfill: this.handleRecallDispatch,
          type: "primary",
          hidden: this.oneBillFlag || ![20, 30].includes(this.status) || this.isAll || this.waybill.waybillType === 10 || this.isClose
        },
        {
          title: "打印",
          plain: true,
          // hidden: !this.showPrintButton || this.hasCloseBacklog,
          hidden: this.oneBillFlag || [-1, 21].includes(this.status) || this.hasCloseBacklog,
          fulfill: this.handlePrint
        }
      ];
    },
    financeFlagTips () {
      return {
        1: "运单已加入对账单，不能操作",
        2: "运单已对账，不能操作",
        3: "运单已结账，不能操作"
      }
    },
    financePayTips () {
      return {
        1: "已收",
        2: "已付",
        3: "已收已付"
      }
    }
  },
  methods: {
    handleClick (button) { },
    handleAccept () {
      this.$confirm("确定接收？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$emit("accept");
      });
    },
    handleAgree () {
      if (this.waybill.finance?.prepayFeeFlag) {
        return this.$message({ type: 'warning', message: `运单${this.financePayTips[this.waybill.finance?.prepayFeeFlag]}预付款，不能操作` });
      } else if (this.waybill.finance?.arrivePayFeeFlag) {
        return this.$message({ type: 'warning', message: `运单${this.financePayTips[this.waybill.finance?.arrivePayFeeFlag]}货到付款，不能操作` });
      } else if (this.waybill.finance?.collectionFeeFlag) {
        return this.$message({ type: 'warning', message: `运单${this.financePayTips[this.waybill.finance?.collectionFeeFlag]}代收货款，不能操作` });
      }
      if (this.waybill.finance?.financeFlag) {
        return this.$message({ type: 'warning', message: this.financeFlagTips[this.waybill.finance?.financeFlag] });
      }

      this.$confirm("确定同意关单？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$emit("agree");
      });
    },
    handleRejectClose () {
      this.$emit("reject", 2);
    },
    handleReject () {
      this.$emit("reject", 1);
    },
    handleSign () {
      this.$emit("sign");
    },
    handleRecallDispatch () {
      if (this.waybill.finance?.prepayFeeFlag) {
        return this.$message({ type: 'warning', message: `运单${this.financePayTips[this.waybill.finance?.prepayFeeFlag]}预付款，不能操作` });
      } else if (this.waybill.finance?.arrivePayFeeFlag) {
        return this.$message({ type: 'warning', message: `运单${this.financePayTips[this.waybill.finance?.arrivePayFeeFlag]}货到付款，不能操作` });
      } else if (this.waybill.finance?.collectionFeeFlag) {
        return this.$message({ type: 'warning', message: `运单${this.financePayTips[this.waybill.finance?.collectionFeeFlag]}代收货款，不能操作` });
      }
      if (this.waybill.finance?.financeFlag) {
        return this.$message({ type: 'warning', message: this.financeFlagTips[this.waybill.finance?.financeFlag] });
      }
      if (this.waybill?.close?.closeTenantId) {
        if (this.waybill?.close?.toTenantId === this.waybill.tenantId && this.waybill?.closeStatus != 40) {
          return this.$message({ type: 'warning', message: `已有待办，请先处理` })
        }
        if (this.waybill?.closeStatus != 40) {
          return this.$message({ type: 'warning', message: `撤回请求已发送，请勿重复操作` })
        }
      }

      if (this.closeFlag) {
        return this.$message({ type: "warning", message: "运单有关单待办需要处理，暂不能操作" });
      }
      this.$emit("recallDispatch");
    },
    handleCancelSplit () {
      this.$confirm("确认撤销拆单？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$emit("cancelSplit");
      });
    },
    handlePrint () {
      const { href } = this.$router.resolve({
        name: this.effectivePaths.includes(this.printPath) ? this.printPath : "TransportPrint",
        query: {
          waybillId: this.waybillId,
          status: this.status,
          orderId: this.waybill.orderId,
          carrier: this.showCarrier ? 1 : 0
        }
      });
      window.open(href, "_blank");
    },

    handleReceipt () {
      this.$emit("receipt");
    }
  }
};
</script>
